package com.easyctba.core.service.impl;

import com.easyctba.common.core.domain.R;
import com.easyctba.common.core.utils.MapstructUtils;
import com.easyctba.common.core.utils.StringUtils;
import com.easyctba.common.mybatis.core.page.TableDataInfo;
import com.easyctba.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easyctba.common.satoken.utils.LoginHelper;
import com.easyctba.core.algorithm.domain.EnglishEntropyResp;
import com.easyctba.core.algorithm.exec.EnglishEntropy;
import com.easyctba.core.enums.EntropyStatus;
import com.easyctba.core.enums.ProjectType;
import com.easyctba.resource.api.RemoteFileService;
import com.easyctba.resource.api.domain.RemoteFile;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import com.easyctba.core.domain.bo.CtbaEntropyBo;
import com.easyctba.core.domain.vo.CtbaEntropyVo;
import com.easyctba.core.domain.CtbaEntropy;
import com.easyctba.core.mapper.CtbaEntropyMapper;
import com.easyctba.core.service.ICtbaEntropyService;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 信息熵分析Service业务层处理
 *
 * @author LionLi
 * @date 2024-02-16
 */
@RequiredArgsConstructor
@Service
public class CtbaEntropyServiceImpl implements ICtbaEntropyService {

    private final CtbaEntropyMapper baseMapper;
    @DubboReference
    private RemoteFileService remoteFileService;

    /**
     * 查询信息熵分析
     */
    @Override
    public CtbaEntropyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询信息熵分析列表
     */
    @Override
    public TableDataInfo<CtbaEntropyVo> queryPageList(CtbaEntropyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CtbaEntropy> lqw = buildQueryWrapper(bo);
        Page<CtbaEntropyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询信息熵分析列表
     */
    @Override
    public List<CtbaEntropyVo> queryList(CtbaEntropyBo bo) {
        LambdaQueryWrapper<CtbaEntropy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CtbaEntropy> buildQueryWrapper(CtbaEntropyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CtbaEntropy> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getProjectId() != null, CtbaEntropy::getProjectId, bo.getProjectId());
        lqw.eq(bo.getCreateTime() != null, CtbaEntropy::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getEntropyText()), CtbaEntropy::getEntropyText, bo.getEntropyText());
        lqw.eq(StringUtils.isNotBlank(bo.getEntropyStatus()), CtbaEntropy::getEntropyStatus, bo.getEntropyStatus());
        lqw.eq(bo.getResult() != null, CtbaEntropy::getResult, bo.getResult());
        return lqw;
    }

    /**
     * 新增信息熵分析
     */
    @Override
    public Boolean insertByBo(CtbaEntropyBo bo) {
        CtbaEntropy add = MapstructUtils.convert(bo, CtbaEntropy.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改信息熵分析
     */
    @Override
    public Boolean updateByBo(CtbaEntropyBo bo) {
        CtbaEntropy update = MapstructUtils.convert(bo, CtbaEntropy.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CtbaEntropy entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除信息熵分析
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 创建项目时初始化信息熵分析表
     * @param projectId 项目id
     * @return 是否成功
     */
    @Override
    public Boolean initEntropy(Long projectId) {
        //设置项目id和entropy_status为upload
        CtbaEntropy ctbaEntropy = new CtbaEntropy();
        ctbaEntropy.setEntropyStatus("upload");
        ctbaEntropy.setProjectId(projectId);
        return baseMapper.insert(ctbaEntropy)>0;
    }

    @Override
    public R<Void> analyze(CtbaEntropyBo bo) {
        CtbaEntropy convert = MapstructUtils.convert(bo, CtbaEntropy.class);
        if (convert==null || StringUtils.isBlank(convert.getEntropyText())){
            return R.fail("分析内容为空");
        }
        String entropyStatus = convert.getEntropyStatus();
        if (!entropyStatus.equals(EntropyStatus.upload)){
            return R.fail("项目状态异常");
        }
        EnglishEntropyResp res= new EnglishEntropy().analyze(convert.getEntropyText());
        //添加结果
        convert.setResult(res.getResult());
        convert.setSize(res.getSize());
        convert.setTime(res.getTime());
        //修改状态
        convert.setEntropyStatus(EntropyStatus.analyze);
        int i = baseMapper.updateById(convert);
        if (i!=1){
            return R.fail("分析失败");
        }
        return R.ok();
    }

    @Override
    public R<CtbaEntropyVo> getInfoByUserAndProject(Long id) {
        if (id==null){
            return R.fail("项目id为空");
        }
        LambdaQueryWrapper<CtbaEntropy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CtbaEntropy::getProjectId,id);
        CtbaEntropyVo ctbaEntropyVo = baseMapper.selectVoOne(wrapper);
        return R.ok(ctbaEntropyVo);
    }

    @Override
    public R<Void> finish(Long id) {
        if (id==null){
            return R.fail("信息熵分析id为空");
        }
        CtbaEntropy ctbaEntropy = baseMapper.selectById(id);
        if (ctbaEntropy==null){
            return R.fail("信息熵分析内容查询错误");
        }
        ctbaEntropy.setEntropyStatus(EntropyStatus.result);
        //生成文件url
        String entropyText = ctbaEntropy.getEntropyText();
        RemoteFile upload;
        //大于10位取前五位字符，否则取所有字符
        if (entropyText.length()>5){
            upload = remoteFileService.upload(entropyText.substring(0, 4) + ".txt", entropyText.substring(0, 4) + ".txt", "text/plain", entropyText.getBytes(StandardCharsets.UTF_8));
        }else {
            upload = remoteFileService.upload(entropyText + ".txt", entropyText + ".txt", "text/plain", entropyText.getBytes(StandardCharsets.UTF_8));
        }
        Long ossId = upload.getOssId();
        ctbaEntropy.setUrl(ossId);
        int i = baseMapper.updateById(ctbaEntropy);
        if (i!=1){
            return R.fail("更新状态失败");
        }
        return R.ok();
    }

    @Override
    public R<Void> pre(Long id) {
        if (id==null){
            return R.fail("信息熵分析id为空");
        }
        CtbaEntropy ctbaEntropy = baseMapper.selectById(id);
        ctbaEntropy.setEntropyStatus(EntropyStatus.upload);
        return baseMapper.updateById(ctbaEntropy)==1 ? R.ok() : R.fail("返回上一步失败");
    }
}
